// pages/posts/postDetail/postDetail.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: { // mark: data
    options:{},
    user_id: 9876567,
    user: 'CurrentUser',
    // 以上为当前用户信息
    post_id: 1234567,
    postTime: '',
    commentNr: '', //暂存输入
    postData: { //暂时先用测试数据，后续根据id从库调用
      _id: '',
      love: false,
      post_data: {
      },
    },
    postComments: [
      
    ],
    comment_ids: [],
  },
  toAnimal() {
    console.log("跳转动物详情页")
    var id = this.data.postData.post_data.animal_id;
    wx.navigateTo({
      url: '/pages/animalDetail/animalDetail?AnimalId='+id,
    })
  },
  commenting(e) {
    this.setData({
      commentNr: e.detail.value,
    })
  },
  sendComment() {
    // console.log("发布评论")
    var id = parseInt(this.data.postData._id)
    let that = this;
    if (this.data.commentNr != '') {
      // var myDate = new Date();
      // var mytime = myDate.getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
      // var simpletime = myDate.toLocaleTimeString();
      // var newComment = {
      //   user_name: this.data.user,
      //   user_id: this.data.id,
      //   post_id: this.data.postData._id,
      //   comment: this.data.commentNr,
      //   time: mytime,
      // }
      // console.log(newComment)
      wx.request({
        url: 'https://api.fracher21.top/spotit/createcomment',
        method: "POST",
        data: {
          token: app.globalData.token,
          id: id, // 评论所属的帖子id
          body: that.data.commentNr, // 评论内容
        },
        success: (res) => {
          // console.log(res.data)
          wx.showToast({
            title: "发布成功",
            icon: "success",
            duration: 3000,
            mask: false,
          })
          that.refreshPage(that.data.options);
        }
      })
      this.setData({
        commentNr: '',
      })
    } else {
      wx.showToast({
        title: "不能发布空内容",
        icon: "error",
        duration: 3000,
        mask: false,
      })
    }

  },
  dianzan() { // mark: dianzan
    var post = this.data.postData;
    var id = parseInt(this.data.post_id);
    // console.log(id)
    // console.log(post)
    if (!post.love) {
      // console.log('zan')
      this.setData({
        ['postData.love']: !post.love,
        [`postData.post_data.dianzan`]: post.post_data.dianzan + 1,
      })
      wx.request({
        url: 'https://api.fracher21.top/spotit/likepost',
        // 取消点赞：	/unlikepost
        method: "POST",
        data: {
          token: app.globalData.token,
          // id: 5
          id: id,
        },
        success: (res) => {
          // console.log(res.data)
        }
      })
    } else {
      // console.log('quxiao')
      this.setData({
        ['postData.love']: !post.love,
        [`postData.post_data.dianzan`]: post.post_data.dianzan - 1,
      })
      wx.request({
        url: 'https://api.fracher21.top/spotit/unlikepost',
        // 取消点赞：	/unlikepost
        method: "POST",
        data: {
          token: app.globalData.token,
          // id: 5 
          id: id,
        },
        success: (res) => {
          // console.log(res.data)
        }
      })
    }
  },
  shoucang(e) { // mark: shoucang
    // console.log('this.shoucang')
    var CurrentPost = this.data.postData;
    console.log(CurrentPost)
    if (!CurrentPost.stared) {
      this.setData({
        [`postData.stared`]: !CurrentPost.stared,
        [`postData.post_data.shoucang`]: CurrentPost.post_data.shoucang + 1,
      })
      wx.request({
        url: 'https://api.fracher21.top/spotit/starpost',
        //				动物			帖子
        // 收藏			/staranimal		/starpost
        // 取消收藏		/unstaranimal	/unstarpost
        method: "POST",
        data: {
          token: app.globalData.token,
          id: CurrentPost._id, // 动物或帖子的id
          // 数据格式一样
        },
        success: (res) => {
          // console.log(res.data) // success: true
        }
      })
    } else {
      this.setData({
        [`postData.stared`]: !CurrentPost.stared,
        [`postData.post_data.shoucang`]: CurrentPost.post_data.shoucang - 1,
      })
      wx.request({
        url: 'https://api.fracher21.top/spotit/unstarpost',
        //				动物			帖子
        // 收藏			/staranimal		/starpost
        // 取消收藏		/unstaranimal	/unstarpost
        method: "POST",
        data: {
          token: app.globalData.token,
          id: CurrentPost._id, // 动物或帖子的id
          // 数据格式一样
        },
        success: (res) => {
          // console.log(res.data) // success: true
        }
      })
    }
  },
  getPostDetail() {
    var id = parseInt(this.data.post_id);
    let that = this;
    wx.request({
      url: 'https://api.fracher21.top/spotit/postinfo',
      method: "GET",
      data: {
        id: id, // 帖子id
        token: app.globalData.token // 可根据用户token显示是否点赞收藏此帖子
        // 若不传递token，则返回未点赞、未收藏
      },
      success: (res) => {
        //  console.log(res.data)
        var post = {
          _id: id,
          love: res.data.liked,
          stared: res.data.stared,
          post_data: {
            tp: res.data.images,
            dianzan: res.data.likes,
            nr: res.data.body,
            firsttime: res.data.time, //毫秒数，后续数据库改为记录这个？
            simpletime: res.data.time,
            userid: res.data.creator.id,
            userphoto: res.data.creator.head,
            username: res.data.creator.name,
            usermotto: res.data.creator.motto,
            shoucang: res.data.stars,
            pinglun: res.data.comments,
            look: res.data.views,
            animal_id:res.data.animals[0],
            location: {
              longitude: res.data.x,
              latitude: res.data.y,
            }
          }
        };
        that.setData({
          postData: post,
        })
      }
    })
  },
  getComments() {
    var id = this.data.post_id;
    let that = this;
    wx.request({
      url: 'https://api.fracher21.top/spotit/listpostcomments',
      method: "GET",
      data: {
        id: id, //id:id,
      },
      success: (res) => {
        // console.log(res.data)
        that.setData({
          comment_ids: res.data.data,
        })
        var commnets = [];
        Promise.all(
          that.data.comment_ids.map((item) => { //每个item是id
            return new Promise((resolve, reject) => {
              wx.request({
                url: 'https://api.fracher21.top/spotit/commentinfo',
                method: "GET",
                data: {
                  id: item, // 评论id，一般是通过请求某一帖子下的评论列表得到（见【15】）
                  token: app.globalData.token, // 带token请求可以得到当前用户是否点赞该评论
                },
                success: (res) => {
                  // console.log(res.data)
                  var tempComment = {
                    user_name: res.data.creator.name,
                    user_id: res.data.creator.id,
                    user_photo: res.data.creator.head,
                    comment: res.data.body,
                    time: res.data.time,
                  }
                  resolve(tempComment);
                }
              })
            })
          })
        ).then((result) => {
          that.setData({
            postComments: result,
          })
        })
      }
    })

  },
  addView() { //增加浏览次数
    var id = parseInt(this.data.post_id);
    wx.request({
      url: 'https://api.fracher21.top/spotit/viewpost',
      method: "POST",
      data: {
        token: app.globalData.token,
        id: id // 帖子id
      },
      success: (res) => {
        //console.log(res.data)
      }
    })
  },
  refreshPage(options){ //mark:页面更新 
    if (options.post_id) {
      // console.log(this.data)
      this.getPostDetail();
      this.getComments();
    } else {
      wx.showToast({
        title: '动态加载错误',
        icon: 'error'
      })
      wx.switchTab({
        url: '/pages/posts/posts',
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  //mark: 周期
  onLoad(options) {
    this.setData({
      options:options,
      post_id: options.post_id,
      // user: options.username,
      // user_id: options.userid,
    })
    // console.log(this.data.post_id)
    this.refreshPage(options);
    this.addView();
    // this.makeTimeFormat(this.data.postData.post_data.firsttime)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.refreshPage(this.data.options);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})